package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/5 19:20
 * @注释
 */
public class TtlConsumer {
    private static final String QUEUE_NAME="ttl_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);
        //从工厂中获取连接
        Connection connection = factory.newConnection();
        //从连接中创建一个频道
        Channel channel = connection.createChannel();
        //创建队列，指定消息过期参数
        Map<String, Object> args1 = new HashMap<>();
        args1.put("x-message-ttl", 5000);
        channel.queueDeclare(QUEUE_NAME, false, false, false, args1);
        System.out.println(" [*] Waiting for message.To exit press CTRL+C");
        //定义如何处理消息
        DeliverCallback deliverCallback=((consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
        });
        //消费消息
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumerTag -> { });
    }
}
